package com.leha.forum.lehare.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leha.forum.lehare.entity.Role;
import com.leha.forum.lehare.service.RolePermissionService;
import com.leha.forum.lehare.service.RoleService;
import com.leha.forum.lehare.mapper.RoleMapper;
import com.leha.forum.lehare.service.UserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
* @author Administrator
* @description 针对表【role】的数据库操作Service实现
* @createDate 2025-04-15 21:44:28
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{
    @Resource
    private RolePermissionService rolePermissionService;
    @Resource
    private UserRoleService userRoleService;

    @Transactional
    @Override
    public boolean deleteRole(Integer roleId) {
        if (roleId <= 0) {
            throw new IllegalArgumentException("角色 ID 无效");
        }

        Role existing = getById(roleId);
        if (existing == null) {
            return false;
        }

        if (rolePermissionService.deleteByRoleId(roleId) && userRoleService.deleteByRoleId(roleId) && removeById(roleId)) {
            return true;
        } else {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    public boolean saveOrUpdateRole(Role role) {
        if (role.getRoleId() != null && role.getRoleId() > 0) {
            Role existing = getById(role.getRoleId());
            if (existing != null) {
                return updateById(role);
            } else {
                throw new IllegalStateException("角色 " + role.getRoleId() + " 不存在");
            }
        } else {
            role.setRoleId(null);
            return save(role);
        }
    }
}




